

import os
import time
import logging
import multiprocessing as mp

import rpyc
from rpyc.utils import server

import dexen
from dexen.system import node
from dexen.system.node.master import master
from dexen.system.node.slave import slave
from dexen.system.base import service
import sys

#===============================================================================
# Globals
#===============================================================================
masters = {}
slaves = {}

#===============================================================================
# Service
#===============================================================================
class NodeService(dexen.Service):
        
    def create_master(self, master_name):
        logger.debug("%s is being created", master_name)
        proc = mp.Process(target=master.start, name=master_name, 
                          args=(master_name, name, rreg_addr)) 
        masters[master_name] = proc
        proc.start()
        logger.debug("%s has started running with id:%d", master_name, proc.pid)
        time.sleep(0.1)
        
    def create_slave(self, slave_name):
        proc = mp.Process(target=slave.start, name=slave_name, 
                          args=(slave_name, name, rreg_addr)) 
        slaves[slave_name] = proc
        proc.start()
        time.sleep(0.1)
            
    def test(self):
        pass
    
#===============================================================================
# Main
#===============================================================================
def main():
    global start_time, name, rreg_addr, logger

    logger = logging.getLogger("NODE")
    handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    format = logging.Formatter("%(name)s: %(message)s")
    
    handler.setFormatter(format)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    
    if not os.path.exists(node.TEMP_DIR):
        os.mkdir(node.TEMP_DIR)

    start_time = time.time()
    ip_addr = service.get_my_ip_addr()
    
    rreg_addr = (sys.argv[1], service.REGISTRY_PORT)
    conn = rpyc.connect(rreg_addr[0], rreg_addr[1])
    #NodeService.ALIASES = [name]
    svr = server.ThreadedServer(NodeService, 
                                protocol_config=service.default_config)
    name = conn.root.register_node(start_time, (ip_addr, svr.port))
    svr.start()


if __name__ == "__main__":
    main()
    
